﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using SWC=System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Reporting.WinForms;
using SQLServerOptimizer.PL.WPF.Datasets.IssuesReportDatasetTableAdapters;
using System.Configuration;
using SQLServerOptimizer.PL.WPF.Datasets;
using System.Windows.Forms;
using AG.Utilities;
using SQLServerHealthCheck.Model;
using SQLServerHealthCheck.SQLServer;
using System.Windows.Forms.Integration;

namespace SQLServerOptimizer.PL.WPF
{
    /// <summary>
    /// Interaction logic for IssuesReportControl.xaml
    /// </summary>
    public partial class IssuesReportControl : SWC.UserControl
    {
        public IssuesReportControl()
        {
         
            InitializeComponent();

        }

       
        // Global Paremeters for the Issue report ServiceId, Service, severityId, database, databaseId.
       public Service instance;
        Database database;
        public HealthCheckDataContext dc;
        public List<Service> SQLServerInstances;

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (MainWindow.IsDatabaseCreated())
            {
                FillSQLServicesCombobox();
            }
        }
  
        private void combobox_Severity_SelectionChanged(object sender, SWC.SelectionChangedEventArgs e)
        {
            try
            {
                RefreshReport();
            }

            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        private void combobox_servicefilter_SelectionChanged(object sender, SWC.SelectionChangedEventArgs e)
        {
            try
            {
                int serviceId = -1;

                if (this.combobox_servicefilter.SelectedIndex != -1)
                {
                    try
                    {
                        instance = (combobox_servicefilter.SelectedItem as Service);

                        serviceId = instance.ServiceID;

                        if (instance != null)
                        {
                            var qry = from db in dc.Databases
                                      where db.ServiceID == instance.ServiceID
                                      select db;

                            List<Database> databases = qry.ToList<Database>();
                            Database dummy = new Database { DatabaseID = -1, DatabaseName = "All" };

                            databases.Insert(0, dummy);

                            this.combobox_databasefilter.ItemsSource = databases;
                            this.combobox_databasefilter.DisplayMemberPath = "DatabaseName";

                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex);
                    }
                }

                RefreshReport();
                this.combobox_databasefilter.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        private void combobox_databasefilter_SelectionChanged(object sender, SWC.SelectionChangedEventArgs e)
        {
            try
            {
                 RefreshReport();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }

        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            RefreshReport();
        }

        public void FillSQLServicesCombobox()
        {
            try
            {
                string conn = System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase");
                CheckInstanceStatusWorker checkinstanceStatusworker = new CheckInstanceStatusWorker(this, conn);

                checkinstanceStatusworker.AccessiblityResult += new InstanceStatusResult(checkinstanceStatusworker_AccessiblityResult);
                checkinstanceStatusworker.Start();
            }
            catch (Exception sql)
            {
                Logger.Error(sql);
            }
        }

        public void RefreshReport()
        {

            try
            {
              
                ReportViewer viewer = (ReportViewer)wfh_rptIssues.Child;

                IssuesTableAdapter adapter = new IssuesTableAdapter();
                adapter.Connection.ConnectionString = ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"];

                IssuesReportDataset dataset = new IssuesReportDataset();

                int databaseId = -1;


                if (this.combobox_databasefilter.SelectedIndex != -1)
                {
                    database = (this.combobox_databasefilter.SelectedItem as Database);
                    databaseId = database.DatabaseID;
                }


                string severity;
                int severityId = -1;

                if (this.combobox_Severity.SelectedIndex != -1)
                {
                    severity = (combobox_Severity.SelectedItem.ToString());

                    if (severity == "High")
                    {

                        severityId = 3;

                    }
                    else if (severity == "Med")
                    {

                      
                        severityId = 2;

                    }

                    else if (severity == "Low")
                    {

                        severityId = 1;

                    }
                    else if (severity == "All")
                    {

                        severityId = -1;

                    }
                }
                else
                {
                    severityId = -1;
                }

                int serviceId = -1;

                if (combobox_servicefilter.SelectedIndex != -1)
                {
                    instance = (combobox_servicefilter.SelectedItem as Service);
                    serviceId = instance.ServiceID;

                }

                string expand = "";
                int expandLevel = 1;

                if (this.combobox_Expand.SelectedIndex != -1)
                {
                    expand = (combobox_Expand.SelectedItem.ToString());

                    if (expand.ToLower() == "none")
                    {

                        expandLevel = 0;

                    }
                    else if (expand.ToLower() == "instances")
                    {
                        expandLevel = 1;
                    }

                    else if (expand.ToLower() == "issues")
                    {
                        expandLevel = 2;
                    }
                }


                adapter.Fill(dataset.Issues, AutoFixControl.High, AutoFixControl.Mid, AutoFixControl.Low, serviceId, databaseId);


                BindingSource bindingSource = new BindingSource();

                bindingSource.DataSource = dataset;
                bindingSource.DataMember = "Issues";


                ReportDataSource reportDataSource = new ReportDataSource();
                viewer.Reset();
                reportDataSource.Name = "Issues";
                reportDataSource.Value = bindingSource;

                ReportParameter param = new ReportParameter("ExpandLevel", expandLevel.ToString());

                viewer.LocalReport.ReportPath = System.Windows.Forms.Application.StartupPath + @"\Reports\Issues.rdlc";
                viewer.LocalReport.DataSources.Add(reportDataSource);
                viewer.LocalReport.EnableHyperlinks = true;
                viewer.BorderStyle = BorderStyle.None;
                viewer.LocalReport.SetParameters(param);
                viewer.RefreshReport();




            }

            catch (Exception ex)
            {
                Logger.Error(ex);
            }





        }
          private void checkinstanceStatusworker_AccessiblityResult(bool accessible)
        {
            try
            {

                if (accessible)
                {
                    dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase"));

                    var qry = from i in dc.Services
                              where i.ServiceTypeID == 1
                              select i;
                    SQLServerInstances = qry.ToList<Service>();
                    Server dummy = new Server { Name = "All" };
                    Service dummyService = new Service { ServiceID = -1, Server = dummy, Name = "" };

                    SQLServerInstances.Insert(0, dummyService);

                    this.combobox_servicefilter.ItemsSource = SQLServerInstances;
                    this.combobox_servicefilter.DisplayMemberPath = "InstanceName";
                    this.combobox_servicefilter.SelectedValuePath = "ServiceID";
                    var main = App.Current.MainWindow as MainWindow;
                    this.combobox_servicefilter.SelectedIndex = main.combobox_servicefilterA.SelectedIndex;
                    instance = (combobox_servicefilter.SelectedItem as Service);
                    var qry2 = from db in dc.Databases
                               where db.ServiceID == instance.ServiceID
                               select db;

                    List<Database> databases = qry2.ToList<Database>();
                    Database dummyDatabase = new Database { DatabaseID = -1, DatabaseName = "All" };

                    databases.Insert(0, dummyDatabase);


                   


                    this.combobox_databasefilter.ItemsSource = databases;
                    this.combobox_databasefilter.DisplayMemberPath = "DatabaseName";

                     // If not a static method, this.MainWindow would work
                    this.combobox_databasefilter.SelectedIndex = main.combobox_databasefilterA.SelectedIndex;

                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
      //private void checkinstanceStatusworker_AccessiblityResult(bool accessible)
      //  {
      //      try
      //      {

      //          if (accessible)
      //          {
      //              dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStringSSHCDatabase"));

      //              var qry = from i in dc.Services
      //                        where i.ServiceTypeID == 1
      //                        select i;
      //              SQLServerInstances = qry.ToList<Service>();
      //              Server dummy = new Server { Name = "All" };
      //              Service dummyService = new Service { ServiceID = -1, Server = dummy, Name = "" };

      //              SQLServerInstances.Insert(0,dummyService);

      //              this.combobox_servicefilter.ItemsSource = SQLServerInstances;
      //              this.combobox_servicefilter.DisplayMemberPath = "InstanceName";
      //              this.combobox_servicefilter.SelectedValuePath = "ServiceID";

      //              this.combobox_servicefilter.SelectedIndex = 0;

      //              List<Database> databases = new List<Database>();
      //              Database dummyDatabase = new Database { DatabaseID = -1, DatabaseName = "All" };

      //              databases.Insert(0, dummyDatabase);


      //              this.combobox_databasefilter.ItemsSource = databases;
      //              this.combobox_databasefilter.DisplayMemberPath = "DatabaseName";
                    
      //              this.combobox_databasefilter.SelectedIndex = 0;

      //          }
      //      } 
      //      catch (Exception ex)
      //      {
      //          Logger.Error(ex);
      //      }
      //  }

        private void combobox_Expand_SelectionChanged(object sender, SWC.SelectionChangedEventArgs e)
        {
            RefreshReport();
        }

        private void wfh_rptIssues_LayoutError(object sender, LayoutExceptionEventArgs e)
        {
                  
            e.ThrowException = false;
        

        }

        
        
    }
}
